package wenjun.du.androidart.ipc.aidl

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.os.RemoteCallbackList
import android.util.Log
import wenjun.du.androidart.ipc.Book
import wenjun.du.androidart.ipc.BookChangeListener
import wenjun.du.androidart.ipc.BookOperation
import java.util.concurrent.CopyOnWriteArrayList

class AidlService : Service() {

    companion object {
        private const val TAG = "AidlService"
    }

    private val mList = CopyOnWriteArrayList<Book>() //线程安全的容器类

    //    private val mListListener = CopyOnWriteArrayList<BookChangeListener>() //线程安全的容器类
    private val mListListener = RemoteCallbackList<BookChangeListener>() //线程安全 并且专门用来注册和解注册的类 底层类似map的数据结构

    private val mBinder: IBinder = object : BookOperation.Stub() {
        override fun addBooks(book: Book?) {
            Log.d(TAG, "addBooks: 添加成功 ")
            mList.add(book)
            for (index in 0 until mListListener.beginBroadcast()) {
                Log.d(TAG, "addBooks: $index")
                mListListener.getBroadcastItem(index).bookChange(book)
            }
            mListListener.finishBroadcast()
        }

        override fun getBook(): MutableList<Book> {
            val mutableListOf = mutableListOf<Book>()
            mutableListOf.addAll(mList)
            return mutableListOf
        }

        override fun registerenListener(listener: BookChangeListener?) {
//            if (!mListListener.contains(listener)) {
            Log.d(TAG, "registerenListener: ====== ")
            mListListener.register(listener)
//            }
        }

        override fun unRegisterenListener(listener: BookChangeListener?) {
//            if (mListListener.contains(listener)) {
            Log.d(TAG, "unRegisterenListener: ====== ")
            mListListener.unregister(listener)
//            }
        }

    }

    override fun onBind(intent: Intent): IBinder {
        return mBinder
    }

    override fun onCreate() {
        val book = Book("第一本书", 10)
        val book2 = Book("第二本书", 10)
        mList.add(book)
        mList.add(book2)
        super.onCreate()
    }
}